package ru.spb.osll.myfit.server.execute;

import java.util.UUID;

import ru.spb.osll.myfit.common.PageExecutingResult;
import ru.spb.osll.myfit.common.PageExecutingResult.PageExecutingState;

public class PageExecutor implements Runnable {

	private PageExecutingResult m_pageResult;
	private String m_id;
	private final String m_pagePath;
	private FitNesseTestRunner m_runner;
	private FixtureListenerImpl m_fixtureListener;
	private PageWriter m_pageWriter;

	public PageExecutor(FitNesseTestRunner runner, String pagePath,
			FixtureListenerImpl listener, PageWriter pageWriter) {
		m_id = UUID.randomUUID().toString();
		m_pagePath = pagePath;
		m_pageResult = new PageExecutingResult(m_id);
		m_runner = runner;
		m_fixtureListener = listener;
		m_pageWriter = pageWriter;
	}

	@Override
	public void run() {
		try {
			synchronized (m_pageResult) {
				m_pageResult.setState(PageExecutingState.PROGRESS);
			}
			String actualPagePath = (m_pagePath != null) ? m_pagePath
					: "FrontPage";
			m_runner.run(actualPagePath);

			synchronized (m_pageResult) {
				m_pageResult.setState(PageExecutingState.FINISH);
			}

			if (m_pageWriter != null)
			  m_pageWriter.writeStream(m_fixtureListener.getOutputStream());
      

		} catch (Exception e) {
			synchronized (m_pageResult) {
				m_pageResult.setState(PageExecutingState.FAIL);
			}
		}
	}

	public String getId() {
		return m_id;
	}
	
	public PageExecutingResult getPageExecutingResult() {
    synchronized (m_pageResult) {
      m_pageResult.removeAllTables();
      m_pageResult.addAllExecutedTable(m_fixtureListener.getTables());
      m_pageResult.setCounts(m_fixtureListener.getCounts());
      return new PageExecutingResult(m_pageResult);
    }
  }
}

